<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>人力资源管理系统 - 薪资历史</title>
  <!-- 引入外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

  <!-- Tailwind配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#2563eb',
            secondary: '#64748b',
            success: '#10b981',
            warning: '#f59e0b',
            danger: '#ef4444',
            dark: '#1e293b',
            light: '#f8fafc'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 引入公共CSS -->
  <link rel="stylesheet" href="css/common.css">

  <!-- 引入API和公共JS -->
  <script src="js/api.js"></script>
  <script src="js/common.js"></script>
</head>
<body class="bg-gray-50 text-gray-800 font-sans">
  <div id="app" class="flex h-screen overflow-hidden"></div>

  <script>
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      if (checkAuthentication()) {
        initPage();
      }
    });

    // 初始化页面
    function initPage() {
      // 加载侧边栏和用户信息
      initSidebar();
      initUserInfo();
      initLogout();

      // 加载薪资历史页面
      loadSalaryHistoryPage();
    }

    // 加载薪资历史页面
    function loadSalaryHistoryPage() {
      showLoading();
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        // 使用真实API调用获取薪资数据
        api.getSalaryHistory()
          .then(response => {
            const salaryData = response.data;
            document.getElementById('app').innerHTML = `
              <!-- 侧边栏 -->
              <aside id="sidebar" class="w-64 bg-white border-r border-gray-200 flex-shrink-0 hidden md:block transition-all duration-300">
                <div class="p-5 border-b border-gray-200">
                  <h1 class="text-xl font-bold text-primary">人力资源管理系统</h1>
                </div>

                <nav class="p-3">
                  <ul></ul>
                </nav>

                <div class="absolute bottom-0 w-full p-4 border-t border-gray-200">
                  <div class="flex items-center gap-3">
                    <img id="userAvatar" src="${user.avatar || 'https://picsum.photos/200/200?random=1'}" alt="用户头像" class="w-10 h-10 rounded-full object-cover">
                    <div>
                      <p id="user" class="font-medium text-sm">${user.name || user.username}</p>
                      <p id="userRole" class="text-xs text-gray-500">${user.role || '普通用户'}</p>
                    </div>
                    <button id="logoutBtn" class="ml-auto text-gray-500 hover:text-danger">
                      <i class="fa fa-sign-out"></i>
                    </button>
                  </div>
                </div>
              </aside>

              <!-- 主内容区 -->
              <main class="flex-1 flex flex-col overflow-hidden">
                <!-- 顶部导航 -->
                <header class="bg-white border-b border-gray-200 h-16 flex items-center justify-between px-6">
                  <div class="flex items-center">
                    <button id="sidebarToggle" class="md:hidden mr-4 text-gray-500">
                      <i class="fa fa-bars text-xl"></i>
                    </button>
                    <h2 id="pageTitle" class="text-lg font-semibold">薪资历史</h2>
                  </div>

                  <div class="flex items-center gap-4">
                    <div class="relative">
                      <input type="text" placeholder="搜索..." id="globalSearch" class="pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary w-64">
                      <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    </div>

                    <button id="notificationBtn" class="relative text-gray-500 hover:text-primary">
                      <i class="fa fa-bell text-xl"></i>
                      <span id="notificationCount" class="absolute -top-1 -right-1 bg-danger text-white text-xs w-4 h-4 rounded-full flex items-center justify-center">3</span>
                    </button>
                  </div>
                </header>

                <!-- 页面内容 -->
                <div class="flex-1 overflow-y-auto p-6">
                  <div class="card mb-6">
                    <h3 class="text-lg font-semibold p-4 border-b border-gray-100">薪资概览</h3>
                    <div class="p-4">
                      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                        <div class="card bg-blue-50 p-4">
                          <p class="text-sm text-gray-500">当前月薪</p>
                          <p class="text-2xl font-bold mt-1">¥${salaryData.currentMonthlySalary.toLocaleString()}</p>
                        </div>
                        <div class="card bg-green-50 p-4">
                          <p class="text-sm text-gray-500">年度总薪资</p>
                          <p class="text-2xl font-bold mt-1">¥${salaryData.annualTotalSalary.toLocaleString()}</p>
                        </div>
                        <div class="card bg-purple-50 p-4">
                          <p class="text-sm text-gray-500">平均月度奖金</p>
                          <p class="text-2xl font-bold mt-1">¥${salaryData.averageMonthlyBonus.toLocaleString()}</p>
                        </div>
                      </div>

                      <div class="h-64 mb-4">
                        <canvas id="salaryTrendChart"></canvas>
                      </div>
                    </div>
                  </div>

                  <div class="card">
                    <h3 class="text-lg font-semibold p-4 border-b border-gray-100">薪资明细</h3>
                    <div class="overflow-x-auto">
                      <table class="w-full">
                        <thead>
                          <tr class="bg-gray-50 text-left">
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">月份</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">基本工资</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">奖金</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">社保公积金</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">个人所得税</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">实发工资</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">状态</th>
                            <th class="px-4 py-3 text-sm font-medium text-gray-500">操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          ${salaryData.details.map(item => `
                            <tr class="border-b border-gray-100">
                              <td class="px-4 py-3 text-sm">${item.month}</td>
                              <td class="px-4 py-3 text-sm">¥${item.basicSalary.toLocaleString()}</td>
                              <td class="px-4 py-3 text-sm">¥${item.bonus.toLocaleString()}</td>
                              <td class="px-4 py-3 text-sm">¥${item.socialSecurity.toLocaleString()}</td>
                              <td class="px-4 py-3 text-sm">¥${item.incomeTax.toLocaleString()}</td>
                              <td class="px-4 py-3 text-sm font-medium">¥${item.netSalary.toLocaleString()}</td>
                              <td class="px-4 py-3 text-sm"><span class="badge ${item.status === '已发放' ? 'bg-success/20 text-success' : 'bg-warning/20 text-warning'}">${item.status}</span></td>
                              <td class="px-4 py-3 text-sm"><button class="text-primary hover:underline" onclick="viewSalaryDetail('${item.month}')">详情</button></td>
                            </tr>
                          `).join('')}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </main>
            `;
            // 确保DOM渲染完成后再初始化侧边栏和图表
            setTimeout(() => {
              initRoleBasedSidebar(user.role);
              // 重新初始化登出功能
              initLogout();
              // 渲染薪资趋势图表
              renderSalaryChart(salaryData.trend);
            }, 0);
          })
          .catch(error => {
            console.error('获取薪资数据失败:', error);
            if (typeof showToast === 'function') {
              showToast('获取薪资数据失败，请重试', 'danger');
            } else {
              alert('获取薪资数据失败，请重试');
            }
          })
          .finally(() => {
            hideLoading();
          });
      } else {
        hideLoading();
        // 处理用户信息不存在的情况
        if (typeof showToast === 'function') {
          showToast('未找到用户信息，请重新登录', 'danger');
        } else {
          alert('未找到用户信息，请重新登录');
        }
        setTimeout(() => {
          window.location.href = 'login.html';
        }, 1500);
      }
    }

    // 查看薪资详情
    function viewSalaryDetail(month) {
      showLoading();
      api.getSalaryDetail(month)
        .then(response => {
          const detail = response.data;
          // 这里可以实现显示详情的逻辑，比如打开模态框
          showToast('查看 ' + month + ' 薪资详情', 'info');
          // 实际应用中可以打开一个模态框展示详细信息
        })
        .catch(error => {
          console.error('获取薪资详情失败:', error);
          showToast('获取薪资详情失败，请重试', 'danger');
        })
        .finally(() => {
          hideLoading();
        });
    }

    // 渲染薪资趋势图表
    function renderSalaryChart(trendData) {
      const ctx = document.getElementById('salaryTrendChart');
      if (ctx) {
        const labels = trendData.map(item => item.month);
        const data = trendData.map(item => item.netSalary);

        new Chart(ctx.getContext('2d'), {
          type: 'line',
          data: {
            labels: labels,
            datasets: [{
              label: '实发工资',
              data: data,
              borderColor: '#2563eb',
              backgroundColor: 'rgba(37, 99, 235, 0.1)',
              tension: 0.3,
              fill: true
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              y: {
                beginAtZero: false,
                ticks: {
                  callback: function(value) {
                    return '¥' + value.toLocaleString();
                  }
                }
              }
            }
          }
        });
      } else {
        console.error('未找到薪资趋势图表Canvas元素');
      }
    }
  </script>
</body>
</html>